package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.service.OrderService;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private WebSocketServer webSocketServer;

    @Value("${sky.shop.address}")
    private String shopAddress;

    @Value("${sky.baidu.ak}")
    private String ak;


    /*
     * 用户下单
     */
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {

        //处理各种业务异常（地址簿为空，购物车数据为空）
        List<AddressBook> addressBookList = addressBookMapper.list(AddressBook.builder().id(ordersSubmitDTO.getAddressBookId()).build());
        if (addressBookList == null || addressBookList.isEmpty()) {
            //用户地址为空，抛出业务异常
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //查询当前用户的购物车数据
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(ShoppingCart.builder().userId(BaseContext.getCurrentId()).build());
        if (shoppingCartList == null || shoppingCartList.isEmpty()) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //检查用户的收货地址是否超出配送范围
        AddressBook addressBook = addressBookList.get(0);
        checkOutOfRange(addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());

        //向订单表插入一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));   //设置订单号
        orders.setStatus(Orders.PENDING_PAYMENT);       //设置订单状态：1 （待付款）
        orders.setUserId(BaseContext.getCurrentId());   //设置订单的用户id
        orders.setOrderTime(LocalDateTime.now());       //设置下单时间
        orders.setPayStatus(Orders.UN_PAID);            //设置订单的支付状态：0  （未支付）
        orders.setConsignee(addressBookList.get(0).getConsignee()); //设置收货人
        orders.setPhone(addressBookList.get(0).getPhone());         //设置用户手机号
        orders.setAddress(addressBookList.get(0).getDetail());      //设置收货地址

        orderMapper.insert(orders);

        List<OrderDetail> orderDetailList = new ArrayList<>();
        //向订单明细表插入n条数据  ( 数据来源于购物车 )
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetailList);

        //清空当前用户的购物车数据
        shoppingCartMapper.deleteByUserId(BaseContext.getCurrentId());
        //封装VO返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .orderAmount(orders.getAmount())
                .build();

        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    @Transactional
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
        JSONObject jsonObject = new JSONObject();
        //直接封装支付成功的code返回值
        jsonObject.put("code","ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        //根据订单号调用 paySuccess() 方法修改订单状态
        paySuccess(ordersPaymentDTO.getOrderNumber());

        //通过WebSocket向客户端浏览器来推送消息 type orderId content
        Orders orders = orderMapper.getByNumber(ordersPaymentDTO.getOrderNumber());
        Long ordersId = orders.getId();

        Map map = new HashMap<>();
        map.put("type",1);                          //  1 表示来单提醒    2 表示客户催单
        map.put("orderId",ordersId);
        map.put("content","订单号："+ordersPaymentDTO.getOrderNumber());
        //将Map集合转换为字符串
        String jsonString = JSON.toJSONString(map);
        //向客户端浏览器推送消息
        webSocketServer.sendToAllClient(jsonString);

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    public OrderVO getOrderDetail(Long id) {
        //根据订单id查询订单表的数据
        Orders orders = orderMapper.getById(id);

        OrderVO orderVO = new OrderVO();

        //数据拷贝
        BeanUtils.copyProperties(orders,orderVO);

        //根据订单id查询订单详细表的数据
        List<OrderDetail>  orderDetails = orderDetailMapper.getByOrderId(id);

        orderVO.setOrderDetailList(orderDetails);

        return orderVO;
    }

    /**
     * 查询历史订单
     * @param ordersPageQueryDTO
     * @return
     */
    public PageResult getPageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        //设置分页
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        //分页条件查询
        Page<Orders> page = orderMapper.list(ordersPageQueryDTO);
        //调用将查询结果封装为OrderVOList集合的方法
        List<OrderVO> orderVOList = getOrderVOList(page);
        return new PageResult(page.getTotal(),orderVOList);
    }

    /**
     * 用户取消订单
     * @param id
     */
    @Transactional
    public void userCancelgetById(Long id) throws Exception {
        //根据订单id查询要取消的订单
        Orders ordersDB = orderMapper.getById(id);
        //查询的订单为空，抛出异常信息
        if(ordersDB == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Integer status = ordersDB.getStatus();
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if(status>3){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();

        // 订单处于待接单状态下取消，需要进行退款,没有营业执照，只能跳过
        if(status == Orders.TO_BE_CONFIRMED ) {
            //调用微信支付退款接口
//            weChatPayUtil.refund(
//                    ordersDB.getNumber(), //商户订单号
//                    ordersDB.getNumber(), //商户退款单号
//                    new BigDecimal(0.01),//退款金额，单位 元
//                    new BigDecimal(0.01));//原订单金额

            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }

        //修改的订单状态为：取消状态
        orders.setId(id);
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orders.setCancelReason("用户取消");
        orderMapper.update(orders);
    }

    /**
     * 催单
     * @param id
     * @return
     */
    public void reminder(Long id) {
        //根据id查询订单
        Orders orders = orderMapper.getById(id);
        //校验订单是否存在
        if(orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Map map = new HashMap();
        map.put("type",2);            //  1 表示来单提醒    2 表示客户催单
        map.put("orderId",orders.getId());
        map.put("content","订单号："+orders.getNumber());
        //通过webSocket向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 再来一单
     * @param id
     */
    @Transactional
    public void repetition(Long id) {
        //思路：根据订单id从订单明细表里查询数据，放到购物车表中

        //根据订单id从订单明细表里查询数据
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(id);
        //利用集合生成stream流和 map 方法用于映射每个元素到对应的结果，得到上次订单的购物车数据
        List<ShoppingCart> shoppingCarts = orderDetails.stream().map(x->{
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(x,shoppingCart,"id");
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setUserId(BaseContext.getCurrentId());
            return shoppingCart;
        }).collect(Collectors.toList());
        //x为形参，相当在遍历 orderDetails 集合里的元素,每次操作需要返回一个元素

        //Collectors 将流转换成集合和聚合元素

        //向购物车表批量插入数据
        shoppingCartMapper.insertBatch(shoppingCarts);
    }

    /**
     * 各个状态的订单数量统计
     * @return
     */
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        //根据订单状态查询订单数量  2待接单 3已接单 4派送中
        orderStatisticsVO.setToBeConfirmed(orderMapper.getStatus(Orders.TO_BE_CONFIRMED));
        orderStatisticsVO.setConfirmed(orderMapper.getStatus(Orders.CONFIRMED));
        orderStatisticsVO.setDeliveryInProgress(orderMapper.getStatus(Orders.DELIVERY_IN_PROGRESS));
        return orderStatisticsVO;
    }


    /**
     * 接单
     * @param ordersConfirmDTO
     */
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        //根据订单id查询
        Orders ordersDB = orderMapper.getById(ordersConfirmDTO.getId());
        if( ordersDB == null ){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Orders orders = new Orders();
        orders.setId(ordersConfirmDTO.getId());
        //设置订单的状态为：接单
        orders.setStatus(Orders.CONFIRMED);
        //根据订单id修改订单的状态为：接单
        orderMapper.update(orders);
    }

    /**
     * 商家拒单
     * @param ordersRejectionDTO
     */
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(ordersRejectionDTO.getId());
        // 订单只有存在且状态为2（待接单）才可以拒单
        if( ordersDB == null ||  !ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED) ){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //订单的支付状态
        Integer PayStatus = ordersDB.getPayStatus();

        Orders orders = new Orders();
        //缺少参数，只能跳过退款服务(支付服务已跳过)
        if(PayStatus == Orders.PAID){
//            String refund = weChatPayUtil.refund(
//                    ordersDB.getNumber(),
//                    ordersDB.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
//            log.info("申请退款：{}", refund);
            //修改订单的支付状态: 退款
            orders.setPayStatus(Orders.REFUND);
        }
        orders.setId(ordersRejectionDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 商家取消订单
     * @param ordersCancelDTO
     */
    public void adminCancel(OrdersCancelDTO ordersCancelDTO) {
        Orders ordersDB = orderMapper.getById(ordersCancelDTO.getId());

        if(ordersDB == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //订单的支付状态
        Integer PayStatus = ordersDB.getPayStatus();

        Orders orders = new Orders();
        //只有订单处于支付状态，商家才能取消订单
        if(PayStatus == Orders.PAID){
//            String refund = weChatPayUtil.refund(
//                    ordersDB.getNumber(),
//                    ordersDB.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
//            log.info("申请退款：{}", refund);
            orders.setPayStatus(Orders.REFUND);
        }
        orders.setId(ordersCancelDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orderMapper.update(orders);
    }

    /**
     * 派送订单
     * @param id
     */
    public void delivery(Long id) {
        Orders ordersDB = orderMapper.getById(id);
        //判断订单存不存在，并且订单的状态为 3 已接单
        if( ordersDB == null ||  !ordersDB.getStatus().equals(Orders.CONFIRMED) ){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(id);
        // 更新订单状态,状态转为派送中
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);
    }

    /**
     * 完成订单
     * @param id
     */
    public void complete(Long id) {
        Orders ordersDB = orderMapper.getById(id);
        // 校验订单是否存在，并且状态为4
        if( ordersDB == null ||  !ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS) ){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(id);
        // 更新订单状态,状态转为完成
        orders.setStatus(Orders.COMPLETED);
        // 更新订单的送达时间
        orders.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(orders);
    }


    public List<OrderVO> getOrderVOList(Page<Orders> page) {
        //需要返回的对象集合
        List<OrderVO> orderVOList = new ArrayList<>();
        //在订单表中查询到的数据集合
        List<Orders> ordersList = page.getResult();
        //判断查询到的数据不为空
       if(ordersList != null && !ordersList.isEmpty()){
           //遍历订单集合获得每个订单对象
           for (Orders orders : ordersList) {
               //获得订单的id
               Long ordersId = orders.getId();
               //根据订单id查询详细的菜品详细
               List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(ordersId);
               /// 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
               List<String> orderDishes = orderDetailList.stream().map(x -> x.getName() + "*" + x.getNumber()).collect(Collectors.toList());

               //封装返回对象
               OrderVO orderVO = new OrderVO();
               BeanUtils.copyProperties(orders,orderVO);
               orderVO.setOrderDetailList(orderDetailList);
               orderVO.setOrderDishes(String.join(" ",orderDishes));
               //将封装好的对象添加到集合中
               orderVOList.add(orderVO);
           }

       }
        return orderVOList;
    }

    /**
     * 检查客户的收货地址是否超出配送范围
     * @param address
     */
    private void checkOutOfRange(String address) {
        Map map = new HashMap();
        map.put("address",shopAddress);
        map.put("output","json");
        map.put("ak",ak);

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address",address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        /*location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin",shopLngLat);
        map.put("destination",userLngLat);
        map.put("steps_info","0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if(distance > 5000){
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }*/
    }
}

